package com.gzc.just.play.last.war.sceneserver.handler;

import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.sceneserver.service.BattleMessageRoutingService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 创建战斗处理器
 * 重构版本：使用BattleMessageRoutingService处理消息
 * 处理创建战斗的消息
 */
@Component
public class CreateBattleHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(CreateBattleHandler.class);
    
    @Autowired
    private BattleMessageRoutingService battleMessageRoutingService;
    
    private static final int CREATE_BATTLE = 1001;
    
    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        try {
            // 从上下文中获取玩家ID
            io.netty.util.AttributeKey<Long> playerIdKey = io.netty.util.AttributeKey.valueOf("playerId");
            Long playerId = ctx.channel().attr(playerIdKey).get();
            if (playerId == null) {
                logger.error("Player ID not found in context, cannot process create battle message");
                return;
            }
            
            // 将消息序列化为字节数组
            byte[] messageBytes = serializeMessage(message);
            
            // 使用消息路由服务处理创建战斗消息
            boolean success = battleMessageRoutingService.routeCreateBattleMessage(ctx, CREATE_BATTLE, messageBytes);
            
            if (!success) {
                logger.error("Failed to handle create battle message for player: {}", playerId);
            }
            
        } catch (Exception e) {
            logger.error("Error handling create battle message", e);
        }
    }
    
    /**
     * 将消息对象序列化为字节数组
     * 实际实现中应该根据具体的消息类型进行序列化
     */
    private byte[] serializeMessage(Object message) {
        try {
            // 实际实现中应该根据具体的消息类型进行序列化
            // 这里返回示例值
            return new byte[0];
        } catch (Exception e) {
            logger.error("Failed to serialize create battle message", e);
            return new byte[0];
        }
    }

    @Override
    public int getMessageId() {
        return CREATE_BATTLE;
    }
    
    @Override
    public String getName() {
        return "CreateBattleHandler";
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
}